
// 文件数据库
const fs = require('fs')
const path = require('path')

const filePath = path.join(__dirname, './data.json')

class Store {
    constructor() {
        this.store = {}
        // 初始化
        try {
            let data = fs.readFileSync(filePath, { encoding: 'utf-8' })
            this.store = JSON.parse(data)
        } catch (error) {
            console.error(error)
        }
    }
    get(k) {
        return this.store[k]
    }
    set(k, v) {
        this.store[k] = v
        this.asyncFile()
    }
    asyncFile() {
        let data = JSON.stringify(this.store);
        fs.writeFile(filePath, data, (err) => {
            if (err) {
                console.log('数据同步错误: ', err)
            } else {
                console.log('数据同步成功')
            }
        })
    }
}

module.exports = new Store()

